#include <iostream>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <unistd.h>
#include "Protocol.hpp" //通过包含同一个协议头文件，使得客户端和服务端形成约定
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage:./client_tcp << server_ip server_port" << std::endl;
        return 1;
    }
    std::string server_ip = argv[1];
    int server_port = std::atoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "Error in creating socket" << std::endl;
        return 2;
    }
    struct sockaddr_in server_addr; // 填充服务器信息结构体
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());
    // client  不需要显示的进行绑定，由OS自动绑定,connect()函数底层会自动绑定
    int n = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (n < 0)
    {
        std::cout << "Error in connecting to server" << std::endl;
        return 3;
    }
    std::string message;

    while (true)
    {
        int x, y;
        char oper;

        std::cout << "input x: ";
        std::cin >> x;
        std::cout << "input y: ";
        std::cin >> y;
        std::cout << "input oper: ";
        std::cin >> oper;
        Request req(x, y, oper);

        // 1,序列化
        req.Serialize(message);

        // 2,endcode
        Encode(message);

        // 3,发送
        n = ::send(sockfd, message.c_str(), message.size(), 0);
        if (n > 0)
        {
            char inbuffer[1024];
            // 4,获得应答
            int m = ::read(sockfd, inbuffer, sizeof(inbuffer));
            if (m > 0)
            {
                inbuffer[m] = '\0';
                std::string respstr = inbuffer;
                std::string content;
                // 4,暂时假设读到的应答是完整的（其实不一定，需要while循环判断）
                Decode(respstr, &content);
                // 5,反序列化
                Response resp;
                resp.Deserialize(content);
                // 6,得到结构化数据
                std::cout << resp.Result() << "[" << resp.Code() << "]" << std::endl;
            }
            else
                break;
        }
        else
            break;
    }

    ::close(sockfd);
    return 0;
}
